//
//  professViewController.m
//  TT
//
//  Created by lanou3g on 16/3/10.
//  Copyright © 2016年 Super磊. All rights reserved.
//

#import "professViewController.h"
#import <Contacts/Contacts.h>
#import <MessageUI/MessageUI.h>
#import "PersonModel.h"
#import "NSString+FirstLetter.h"

@interface professViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    CNContact *contacts;
    CNPhoneNumber *phoneNumbers;
}
@property (weak, nonatomic) IBOutlet UITableView *tableV;
@property (nonatomic,strong)PersonModel *model;
///分组后的所有联系人
@property (nonatomic,strong)NSMutableDictionary *personDic;
@property (nonatomic,strong)NSMutableArray *personArray;

///排好序的首字母数组
@property (nonatomic,strong)NSMutableArray *arrayAllKeys;

@property (nonatomic,strong)NSIndexPath *indexpath;


@end

@implementation professViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.tableV];
    
//    获取手机通讯录
    [self getBook];
    self.personDic = [self changeWithArray:self.personArray];
    self.arrayAllKeys = [self.personDic.allKeys sortedArrayUsingSelector:@selector(compare:)].mutableCopy;
    NSMutableArray *arr0 = [NSMutableArray array];
    [self.personDic setObject:arr0 forKey:@"0"];
}


-(NSMutableArray *)getBook{
    if (_personArray == nil) {
        _personArray = [NSMutableArray array];
    }
//    新建一个通讯录类
    CNContactStore *addressBooks = nil;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        addressBooks = [[CNContactStore alloc]init];
//        获取通讯录权限
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        [addressBooks requestAccessForEntityType:(CNEntityTypeContacts) completionHandler:^(BOOL granted, NSError * _Nullable error) {
             dispatch_semaphore_signal(sema);
        }];
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        addressBooks = [CNContactStore new];
    }
//    NSPredicate *predicate = nil;
//    self.personArray = [addressBooks unifiedContactsMatchingPredicate:predicate keysToFetch:@[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey] error:nil].mutableCopy;
//    
//    NSLog(@"%@",self.personArray);
    
    
    
    
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc]initWithKeysToFetch:@[CNContactPhoneNumbersKey,CNContactGivenNameKey,CNContactFamilyNameKey]];
    
    [addressBooks enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        contacts = contact;
      NSArray *number =  contact.phoneNumbers;
        for (CNLabeledValue *v in number) {
            phoneNumbers = v.value;
//            NSLog(@"%@",phoneNumbers.stringValue);
        }
//        新建一个model类
        PersonModel *model = [[PersonModel alloc]init];
        model.phoneNumbers = phoneNumbers.stringValue;
        model.givenName = contacts.givenName;
        model.familyName = contacts.familyName;

        [self.personArray addObject:model];
       
        
    }];
    
    
    
    /*
    //获取通讯录中所有人
//    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
    //通讯录中人数
//    CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);
    //循环，获取每个人的个人信息
    for (NSInteger i = 0; i < nPeople; i++)
    {
        //新建一个addressBook model类
        PersonModel *model = [PersonModel new];
        //获取个人
        ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
        //获取个人名字
        CFTypeRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
        CFTypeRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
        CFStringRef abFullName = ABRecordCopyCompositeName(person);
        NSString *nameString = (__bridge NSString *)abName;
        NSString *lastNameString = (__bridge NSString *)abLastName;
        if ((__bridge id)abFullName != nil) {
            nameString = (__bridge NSString *)abFullName;
          } else {
            if ((__bridge id)abLastName != nil)
            {
                nameString = [NSString stringWithFormat:@"%@ %@", nameString, lastNameString];
                
            }
        }
        model.name = nameString;
        model.recordID = (int)ABRecordGetRecordID(person);;
        ABPropertyID multiProperties[] = {
            kABPersonPhoneProperty,
            kABPersonEmailProperty
        };
        NSInteger multiPropertiesTotal = sizeof(multiProperties) / sizeof(ABPropertyID);
        for (NSInteger j = 0; j < multiPropertiesTotal; j++) {
            ABPropertyID property = multiProperties[j];
            ABMultiValueRef valuesRef = ABRecordCopyValue(person, property);
            NSInteger valuesCount = 0;
            if (valuesRef != nil) valuesCount = ABMultiValueGetCount(valuesRef);
            if (valuesCount == 0) {
                CFRelease(valuesRef);
                continue;
            }
            //获取电话号码和email
            for (NSInteger k = 0; k < valuesCount; k++) {
                CFTypeRef value = ABMultiValueCopyValueAtIndex(valuesRef, k);
                switch (j) {
                    case 0: {// Phone number
                        model.tel = (__bridge NSString*)value;
                        break;
                    }
                    case 1: {// Email
                        model.email= (__bridge NSString*)value;
                        break;
                    }
                }
                CFRelease(value);
            }
            CFRelease(valuesRef);
        }
        */
        //将个人信息添加到数组中，循环完成后addressBookTemp中包含所有联系人的信息
    
       return _personArray;

}

//将数组转换为分组字典
- (NSMutableDictionary *)changeWithArray:(NSMutableArray *)array {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (PersonModel *model in array) {
        NSString *firstName = [[model.givenName pinyinOfName] uppercasePinYinFirstLetter];
        NSMutableArray *arr = nil;
        if (![dic.allKeys containsObject:firstName]) {
            arr = [NSMutableArray array];
            [dic setValue:arr forKey:firstName];
            
        }
        [dic[firstName] addObject:model];
    }
    return dic;
}

#pragma mark - UITableView Delegate and Datasource functions
//有几组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arrayAllKeys.count+1;
}
//每组几个
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return [self.personDic[@"0"] count];
    }
    NSString *key = self.arrayAllKeys[section-1];
    return [self.personDic[key] count];
    
}
//图视图高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
//间隔
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
//每行宽度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
//cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"ContactCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    if (indexPath.section == 0) {
        PersonModel *modell = self.personDic[@"0"][indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",modell.givenName,modell.familyName];
//        cell.detailTextLabel.text = modell.phoneNumbers;
        return cell;
    }
    NSString *key = self.arrayAllKeys[indexPath.section-1];
    PersonModel *modell = self.personDic[key][indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",modell.givenName,modell.familyName];
//    cell.detailTextLabel.text = modell.phoneNumbers;
    return cell;
}
//每组的名称
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return [NSString stringWithFormat:@"已表白(%ld)人",[self.personDic[@"0"] count]];
    }else{
    return self.arrayAllKeys[section-1];
    }
}
//索引
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.arrayAllKeys;
}

//选择的cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *key = self.arrayAllKeys[indexPath.section-1];
    PersonModel *modell = self.personDic[key][indexPath.row];
    self.model = modell;
    self.indexpath = indexPath;
    NSString * phoneNumber = [modell.phoneNumbers stringByReplacingOccurrencesOfString:@"-" withString:@""];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否发送短信" preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"否" style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"是" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *key = self.arrayAllKeys[self.indexpath.section-1];
        PersonModel *modell = self.personDic[key][self.indexpath.row];
        if ([self.personDic[key] count] == 1) {
            [self.personDic removeObjectForKey:key];
            NSInteger sec = self.indexpath.section;
            [self.arrayAllKeys removeObjectAtIndex:sec - 1];
//            [self.tableV deleteSections:[NSIndexSet indexSetWithIndex:self.indexpath.section] withRowAnimation:UITableViewRowAnimationNone];
        } else {
            [self.personDic[key] removeObjectAtIndex:self.indexpath.row];
//            [self.tableV deleteRowsAtIndexPaths:@[self.indexpath] withRowAnimation:UITableViewRowAnimationNone];
        }
        
        [self.personDic[@"0"] insertObject:modell atIndex:0];
//        [self.tableV moveRowAtIndexPath:self.indexpath toIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        
//        [self.tableV insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        [self.tableV reloadData];
        [self sendSmsMessageWithPhoneNumber:phoneNumber];
    }];
    [alert addAction:action];
    [alert addAction:action1];
    [self presentViewController:alert animated:YES completion:nil];
    
}
//是否可以移动
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
//移动
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    
    NSString *key = self.arrayAllKeys[sourceIndexPath.section];
    PersonModel *model = self.personDic[key][sourceIndexPath.row];
    [self.personDic[key] removeObjectAtIndex:sourceIndexPath.row];
    [self.personDic[key] insertObject:model atIndex:destinationIndexPath.row];
    
}



#pragma mark - 短信
-(void)sendSmsMessageWithPhoneNumber:(NSString *)phoneNumber
{
    if([MFMessageComposeViewController canSendText])
    {
        [self displaySMSComposerSheetPhoneNumber:phoneNumber];
    }
    else
    {
        UIAlertController *msg = [UIAlertController alertControllerWithTitle:@"提示" message:@"该设备不支持发短信" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        [msg addAction:action];
        [self presentViewController:msg animated:YES completion:nil];
//        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该设备不支持发短信" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
//        [msgbox show];
    }
}
-(void)displaySMSComposerSheetPhoneNumber:(NSString *)phoneNumber
{
    MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
    picker.messageComposeDelegate = (id<MFMessageComposeViewControllerDelegate>)self;
    
    picker.recipients = [NSArray arrayWithObject:phoneNumber];
    
    picker.body=[NSString stringWithFormat:@"%@,%@",self.model.givenName,LOVEMESSAGE];
    
    [self presentViewController:picker animated:YES completion:nil];
    
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
                 didFinishWithResult:(MessageComposeResult)result {
    
    switch (result)
    {
        case MessageComposeResultCancelled:
            NSLog(@"Result: SMS sending canceled");
            break;
        case MessageComposeResultSent:{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"发送成功" preferredStyle:(UIAlertControllerStyleActionSheet)];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"知道了" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                
//                    NSString *key = self.arrayAllKeys[self.indexpath.section-1];
//                    PersonModel *modell = self.personDic[key][self.indexpath.row];
//                    [self.personDic[key] removeObjectAtIndex:self.indexpath.row];
//                    [self.personDic[@0] insertObject:modell atIndex:0];
//                    [self.tableV moveRowAtIndexPath:self.indexpath toIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                   
                }];
            
            [alert addAction:action1];
            [self presentViewController:alert animated:YES completion:nil];
            NSLog(@"Result: SMS sent");
        }
            break;
        case MessageComposeResultFailed:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"提示" message:@"短信发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            
            [msgbox show];
            
        }
            break;
        default:
            NSLog(@"Result: SMS not sent");
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
    
#pragma mark 懒加载
- (NSMutableDictionary *)personDic {
    if (!_personDic) {
        _personDic = [NSMutableDictionary dictionary];
    }
    return _personDic;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
